<?php
session_start();
require_once 'db_connect.php';
require_once 'HerbManager.php';

// 检查用户是否已登录
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
    http_response_code(401);
    echo json_encode(['error' => '请先登录']);
    exit;
}

$herbManager = new HerbManager();
$query = $_GET['query'] ?? '';
$id = $_GET['id'] ?? '';

// 如果提供了ID，按ID搜索单个药材
if ($id) {
    $herb = $herbManager->getHerbById($id);
    header('Content-Type: application/json');
    if ($herb) {
        echo json_encode([$herb]);
    } else {
        echo json_encode([]);
    }
    exit;
}

// 如果提供了查询词，按名称搜索
if ($query) {
    $results = $herbManager->searchHerbs($query);
    header('Content-Type: application/json');
    echo json_encode($results);
    exit;
}

echo json_encode([]);
?>